#include "winsock2.h"
#include "iostream"

using namespace std;

#define SERVER_IP "127.0.0.1"
#define PORT 8080
#define BUFFER_SIZE 1024

int main() {
    WSADATA wsaData;
    SOCKET sock;
    struct sockaddr_in serv_addr;

    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        printf("WSAStarup 初始化失败, 错误码:%d \n", WSAGetLastError());
        return 1;
    }

    // 1. 创建socket
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Socket 创建失败, 错误码: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(SERVER_IP); // inet_addr(SERVER_IP) 将字符串IP转换为无符号32位整数
    serv_addr.sin_port = htons(PORT);   // 将主机字节序(小端)转换为网络字节序(大端)

    // 2. connect连接服务器地址
    if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == SOCKET_ERROR) {
        printf("连接失败, 错误码: %d\n", WSAGetLastError());
        closesocket(sock);
        WSACleanup();
        return 1;
    }

    // 3. 发送和接收数据
    const char* request = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
    send(sock, request, (int)strlen(request), 0);
    printf("请求已发送.\n");

    // 4. 从服务端接收数据
    char buffer[BUFFER_SIZE] = {0};
    int valread = recv(sock, buffer, BUFFER_SIZE, 0);
    if (valread > 0) {
        buffer[valread] = '\0';
        printf("服务器响应数据:\n%s\n", buffer);
    } else {
        printf("服务器未响应.\n");
    }

    // 5. close关闭socket
    closesocket(sock);   // 这里也给服务端的socket发送关闭信号

    WSACleanup();
    return 0;
}